function networkDelayTime(times: number[][], n: number, k: number): number {
  let visited = new Array(n).fill(Infinity);
  visited[k-1] = 0;
  let links = new Array(n).fill(0).map(_ => new Array(n).fill(-1));
  times.forEach( ([s,t,c]) => {
      links[s - 1][t - 1] = c;
  });
  function go(s: number,nt: number, route: number[]): void{
      let link = links[s];
      for(let i = 0; i < n; i ++) {
          if(link[i] >= 0 && !route.includes(i)) {
              visited[i] = Math.min(nt + link[i], visited[i]);
              go(i, nt + link[i], [...route, s]);
          }
      }
  }
  go(k - 1, 0, []);
  console.log(links);
  let ret = 0;
  for(let i of visited){
      if(!Number.isFinite(i)) return -1;
      ret = Math.max(ret,i);
  }
  return ret;
};


// function networkDelayTime(times: number[][], n: number, k: number): number {
//   let visited = new Array(n).fill(Infinity);
//   visited[k-1] = 0;
//   let links = new Array(n).fill(0).map(_ => new Array(n).fill(-1));
//   times.forEach( ([s,t,c]) => {
//       links[s - 1][t - 1] = c;
//   });
//   function go(s: number,nt: number): void{
//       let link = links[s];
//       for(let i = 0; i < n; i ++) {
//           if(link[i] >= 0 && nt + link[i] < visited[i]) {
//               visited[i] = nt + link[i];
//               go(i, nt + link[i]);
//           }
//       }
//   }
//   go(k - 1,0);
//   let ret = 0;
//   for(let i of visited){
//       if(!Number.isFinite(i)) return -1;
//       ret = Math.max(ret,i);
//   }
//   return ret;
// };

console.log(networkDelayTime([[3,5,78],[2,1,1],[1,3,0],[4,3,59],[5,3,85],[5,2,22],[2,4,23],[1,4,43],[4,5,75],[5,1,15],[1,5,91],[4,1,16],[3,2,98],[3,4,22],[5,4,31],[1,2,0],[2,5,4],[4,2,51],[3,1,36],[2,3,59]]
  ,5,
  5));